package controllers

import (
	"fmt"
	"github.com/astaxie/beego"
	"beego-curd/models"
	"strconv"
)

/**
Home控制器
*/
type HomeController struct {
	beego.Controller
}

//get请求用户列表 执行的方法
func (c *HomeController) Get() {
	//var user = new(models.User)
	//查询用户列表
	userlist := models.DataList()
	c.Data["datas"] = userlist
	c.TplName = "home.html"
}

//删除方法
type DeleteHomeController struct {
	beego.Controller
}

func (this *DeleteHomeController) Get() {
	id, _ := this.GetInt64("id")
	result, err := models.DeleteById(id)
	if result == true {
		this.Data["json"] = "删除成功"
	} else {
		this.Data["json"] = err
	}
	this.ServeJSON()
}

//编辑信息界面
type EditHomeController struct {
	beego.Controller
}

func (c *EditHomeController) Get() {
	//用户列表
	idval, errId := strconv.ParseInt(c.GetString("id"), 10, 60)
	if errId != nil {

		fmt.Println("缺少参数id")
	}

	user, err := models.QueryById(idval)
	if err == true {
		fmt.Println(err)
	}
	fmt.Println(user)
	c.Data["data"] = user
	c.TplName = "edit.html"
}

type UpdateHomeController struct {
	beego.Controller
}

func (c *UpdateHomeController) Post() {
	// 获取参数
	id, _ := c.GetInt("Id", 0)
	// 创建模型对象
	UserData := models.User{
		Name:     c.GetString("name"),
		Nickname: c.GetString("nickname"),
		Pwd:      c.GetString("pwd"),
		Sex:      c.GetString("sex"),
		Email:    c.GetString("email"),
		Phone:    c.GetString("phone"),
		Status:   1,
	}
	//新增用户
	if id == 0 {
		//新增一条数据，并给模型赋值
		user := models.CreateUser(UserData, int64(id))
		fmt.Println(user)
	} else {
		// 使用QuerySeter 进行数据更新
		//fields := make(map[string]interface{})
		//fields["Id"] = id
		//fields["Name"] = c.GetString("name")
		//fields["Nickname"] = c.GetString("nickname")
		//fields["Pwd"] = c.GetString("pwd")
		//fields["Sex"] = c.GetString("sex")
		//fields["Email"] = c.GetString("email")
		//fields["Phone"] = c.GetString("phone")
		//models.UpdateById(id, "user", fields)

		// 直接使用模型对象更新
		UserData.Id = int64(id)
		_, err := models.UpdateData(UserData)
		if err != nil {
			fmt.Println(err)
		}

	}
	//路径的跳转
	c.Redirect("/Home/List", 302)
}

//控制器
type UserController struct {
	beego.Controller
}

//get请求用户分页列表 执行的方法
func (c *UserController) Get() {
	//得到当前分页html的数据
	pa, err := c.GetInt("page")
	if err != nil {
		println(err)
	}
	pre_page := 3
	totals := models.GetDataNum()
	res := models.Paginator(pa, pre_page, totals)
	//得到分页user的数据
	userlist := models.LimitList(3, pa)
	c.Data["datas"] = userlist //用户的数据
	c.Data["paginator"] = res  //分页的数据
	c.Data["totals"] = totals  //分页的数据
	c.TplName = "list.html"
}
